<?php
/**
 * Created by PhpStorm.
 * User: 小蛮哼哼哼
 * Email: 243194993@qq.com
 * Date: 2022/3/22
 * Time: 10:52
 * motto: 现在的努力是为了小时候吹过的牛逼！
 */

namespace app\api\model;

use app\common\model\TimeModel;
use think\Exception;
use think\facade\Log;

class WeixinUser extends TimeModel
{
    /**
     * @param array $data
     * @return array|void
     * @throws Exception
     */
    public function getUserByOpenid(array $data = [])
    {
        //查询是否存在 存在则返回 不存在则插入
        try {
            $wechat = $this->getUserInfo($data['openid']);
        } catch (\Exception $e) {
            throw new Exception("查询失败");
        }
        if ($wechat) {
            return $wechat->toArray();
        } else {
            try {
                $res = $this->save($data);
            } catch (\Exception $e) {
                throw new Exception("新增失败");
            }
            if ($res) {
                $result = $this->getUserInfo($data['openid']);
                if ($result) {
                    return $result->toArray();
                } else {
                    throw new Exception("用户不存在");
                }
            } else {
                throw new Exception("增加失败");
            }
        }
    }

    /**
     * @param array $data
     * @return array
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function updateByUserInfo(array $data = [])
    {
        $data['update_time']=time();
        try {
            $result = $this->where('openid', $data['openid'])->update($data);
        } catch (\Exception $e) {
            Log::error($e->getMessage() . " " . $e->getFile() . " " . $e->getCode());
            throw new Exception("内部错误");
        }
        if ($result) {
            $res = $this->getUserInfo($data['openid']);
            if ($res) {
                return $res->toArray();
            } else {
                throw new Exception("用户不存在");
            }
        } else {
            throw new Exception("用户信息不存在");
        }
    }

    /**
     * @param string $openid
     * @return WeixinUser|array|mixed|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function getUserInfo(string $openid = '')
    {
        return $this->where('openid', $openid)
            ->find();
    }
}